package hevs.activities;

import hevs.greencontrol.R;
import hevs.greencontrol.R.id;
import hevs.greencontrol.R.layout;
import hevs.utils.ConnectionManager;
import hevs.utils.Error;
import hevs.utils.Utils;

import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * This class allow the user to register in the application.
 * @author Jonathan Moreira, Jun Yang, Natal Venetz, Ivan Samardziev
 *
 */
public class Registration extends Activity implements OnClickListener{

	// DATA
	private EditText username;
	private EditText password;
	private EditText passwordAgain;
	private Button registerButton;
	
	/**
	 * Method called on creation of activity
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registration);
		
		// instanciate the edit boxes
		username = (EditText) findViewById(R.id.username_register);
		password = (EditText) findViewById(R.id.password_register);
		passwordAgain = (EditText) findViewById(R.id.password_again);

		// instanciate the button
		registerButton = (Button) findViewById(R.id.register_button);
	}
	
	/**
	 * Method called on start of activity
	 */
	@Override
	protected void onStart()
	{
		super.onStart();

		// give the button a listener control
		registerButton.setOnClickListener(this);
	}
	
	/**
	 * Switch the actions when executed on click
	 */
	@Override
	public void onClick(View view)
	{
		if(view.getId() == R.id.register_button)
		{
			// Validation of the text fields
			if(username.getText().toString().equals("") ||
					password.getText().toString().equals("") ||
					passwordAgain.getText().toString().equals(""))
			{
					Error.toastNotif(this, "Error: all the fields are required", 2);
					return;
			}
			
			if(!password.getText().toString().equals(passwordAgain.getText().toString()))
			{
					Error.toastNotif(this, "Error: passwords are different", 2);
					return;
			}
			
			// Adding the nabaztag through the webservice
			ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();

			nameValuePairs.add(new BasicNameValuePair("userName",username.getText().toString()));
			nameValuePairs.add(new BasicNameValuePair("userPassword",password.getText().toString()));

			JSONArray jArray = ConnectionManager.sendhttpPost("addUser.php", nameValuePairs);
			
			// If the add has commited correctly
			boolean pass = Utils.getRegisterConfirmation(jArray, this);
			
			if(pass)
			{
				startActivity(new Intent(this,StartPage.class));
				this.finish();
			}
		}
	}


}
